<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\Image;
use EasyWeChat\Message\News;
//use App\User;
use DB;
use \cache;

class WxxController extends Controller
{

    public $app = null;
    public $arr_openid = [ 'o3eaus6PSrb7iEjqZ__Mtq_kuNsU','o3eaus8lUvK0eiWB2n4iU1TAdeDs','o3eaus0YpPcM62Xy15BvvFS-B4do'  ];
    public function __construct(){
        $options = [
          'debug'  => true,
          'app_id' => 'wxb07775315e81c55f',
          'secret' => 'dfb1fbcec72fd7a9a1b5ebf5e9a135a9',
          'token'  => 'johntest',
          // 'aes_key' => null, // 可选
          'log' => [
              'level' => 'debug',
              'file'  => '/tmp/easywechat.log', // XXX: 绝对路径！！！！
          ],


          'guzzle'=>[
            'timeout'=>5.0,
            'verify'=>false,
          ]
          //...
        ];
      $this->app = new Application($options);
    }
    //
    public function index(){
      $server = $this->app->server;
      $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
       $server->setMessageHandler(function($message){
      //     // 注意，这里的 $message 不仅仅是用户发来的消息，也可能是事件
      //     // 当 $message->MsgType 为 event 时为事件
          if ($message->MsgType == 'event') {
			$text = new Text( ['content'=>"
燕子在家，守护爸妈



第一步：回复1，如何绑定设备
第二步：回复2，详细界面介绍
第三步：回复3，设备声音说明.
"] );
//return $text;
		if( $message->Event == 'LOCATION' ){
		$openId = $message->FromUserName;//openid
		        $user = DB::table('tbmember')->where('openID',$openId)->first();  //名字
			$name = $user->name;
			$x = $message->Latitude;
			$y = $message->Longitude;
			$p = $message->Precision;
			$times = date( 'Y-m-d H:i:s' , time() );
			//return $name;
		 	DB::table( 'tblocation'  )->insert( ['openID'=>$openId, 'openid_name'=>$name , 'datetime'=>$times , 'location-x'=>$x , 'location-y'=>$y,'Precision'=>$p  ]  );
		//	return "您的地理位置维度\n".$message->Latitude."\n您的地理位置精度\n".$message->Longitude;
		}elseif($message->Event == 'subscribe') {
                  return $this->guanzhu($message);
              }elseif ($message->Event == 'unsubscribe') {
                  $this->quxiao($message);
              }elseif($message->Event == 'CLICK'){

		        $content = $message->EventKey;
			//return $content;
                if( $content == 'use_help' ){
			$text = new Text(['content' => "微信，
我们每天要十几次的查看:
浏览朋友圈，看别人的生活……
其实老爸老妈才是我们更该时时关注的。
现在，在这里，终于也可以随时看爸妈的“朋！友！圈！”了。
不仅安全和健康情况一目了然，
和爸妈的心也更近了！

谢谢您选用燕子智能，
随时欢迎您的任何意见和建议。
为了爸妈！

回复“说明”，查看详细界面介绍
回复“绑定”，查看绑定设备方法
回复“声音”，查看设备声音说明"]);
//	$text = new Text( ['content'=>"
//燕子在家，守护爸妈



//第一步：回复1，如何绑定设备
//第二步：回复2，详细界面介绍
//第三步：回复3，设备声音说明
//"] );
                                return $text;
             	 }else if ( $content == 'kaifa_loading' )
		{
			$text = new Text( [ 'content'=>'开发中' ] );
			return $text;
		}
              }
/****************************CLICK事件结束 *********************************/


          }else if ( $message->MsgType == 'text' ){
			if ( $message->Content == 'pc' ){
				return 'www.laoyou1.me/alcenter';
			}elseif ( $message->Content == 'private' ){

			}else if ( $message->Content == 'latest' ){
                                return 'http://www.laoyou1.me/shhomer/output/latest.php';
                        }else if ( $message->Content == 'offline' ){
                                return 'http://www.laoyou1.me/shhomer/output/Offline.php';
                        }else if ( $message->Content == 'visit' ){
                                return 'http://www.laoyou1.me/shhomer/output/Vister.php';
			}else if ( $message->Content == '1' || $message->Content == '绑定'  ){
				 $url = 'http://www.laoyou1.me/bangding.php?time'.time();
                                $img = 'http://www.laoyou1.me/version1.3/img/wg29.jpg';
                                $news = new News();
                                $news->title = '怎么绑定设备';
                                $news->description = '现在微信里找到我们的公众号 "燕子在家" ...';
                                $news->url= $url;
                                $news->image = $img;
                                return [$news];
			}else if ( $message->Content == '听到'  ){
                                $media = "P-ikLeDd5U9dPIf15SyEhe9aVqjmsQMqgSwfSPkppD8kBZmP-taRMaQLOkSF7t-u";
                                $text = new Image();
                                $text->media_id = $media;
                        }
			else if ( $message->Content == 'yanzishouquan' )
			{
				 $open = $message->FromUserName;

				if( !in_array( $open , $this->arr_openid  )  )
				{
					return ;
				}
				$open = $message->FromUserName;

				$now = time();
                                $url = 'http://www.laoyou1.me/hefei/login/index.php?type=shuoming&openid='.$open.'&time='.$now;
                                $img = 'http://www.laoyou1.me/version1.3/img/he.jpg';
                                $news = new News();
                                $news->title = '设备授权';
                                $news->description = '现在微信里找到我们的公众号 "燕子在家" ...';
                                $news->url= $url;
                                $news->image = $img;
				return $news;
			}
			  else if ( $message->Content == 'yanzidelete' )
                        {
                                 $open = $message->FromUserName;

                                if( !in_array( $open , $this->arr_openid  )  )
                                {
                                        return ;
                                }
                                $open = $message->FromUserName;

                                $now = time();
                                $url = 'http://www.laoyou1.me/hefei_del/login/index.php?type=shuoming&openid='.$open.'&time='.$now;
                                $img = 'http://www.laoyou1.me/version1.3/img/he.jpg';
                                $news = new News();
                                $news->title = '设备删除';
                                $news->description = '现在微信里找到我们的公众号 "燕子在家" ...';
                                $news->url= $url;
                                $news->image = $img;
                                return $news;
                        }
			else if ( $message->Content == '1' ){
				$url = 'http://www.laoyou1.me/Ajax.pdf';
				$img = 'http://www.laoyou1.me/version1.3/img/yuan.png';
				$news = new News();
				$news->title = 'EasyWeChat';
				$news->description = '微信 SDK ...';
				$news->url= $url;
				$news->image = $img;
			}else if ( $message->Content == '2' || $message->Content == '说明'  ){
				$now = time();
				$url = 'http://www.laoyou1.me/shuoming.php?type=shuoming&time='.$now;
                                $img = 'http://www.laoyou1.me/version1.3/img/he.jpg';
                                $news = new News();
                                $news->title = '看懂界面';
                                $news->description = '现在微信里找到我们的公众号 "燕子在家" ...';
                                $news->url= $url;
                                $news->image = $img;
                                return [$news];
			}else if ( $message->Content == '3' || $message->Content == '声音'  ){
                                 $media = "x6J_Wm3GKmldyirzD5x8YzFBrhDKdAmIVW79q1uKXYI";
                                $text = new Image();
                                $text->media_id = $media;
                                return $text;
                        }else if ( $message->Content == '11'  ){
                                return $message->FromUserName;
                        }else if ( $message->Content == 'new' ){
				return "http://www.laoyou1.me/chart1.7/index.php?openid=o3eaus8lUvK0eiWB2n4iU1TAdeDs&did=SIMCOM_SIM800C861694035951209&gatename=1209";
		}else if ( $message->Content =='boss' ){
			return 'http://www.laoyou1.me/chart1.7/index.php?openid=o3eaus6PSrb7iEjqZ__Mtq_kuNsU&did=SIMCOM_SIM800C861694036012266&gatename=5480姜';
		}else if ( $message->Content =='he' ){
			return 'http://www.laoyou1.me/chart1.7/index.php?openid=o3eaus0YpPcM62Xy15BvvFS-B4do&did=SIMCOM_SIM800C861694035887130&gatename=薛';
		}
		else if( $message->Content == 'tel'  )
		{
			$yuxing_arr = [];
			$yuxing_arr[] = 'o3eaus6PSrb7iEjqZ__Mtq_kuNsU';//姜总
			$yuxing_arr[] = 'o3eaus0YpPcM62Xy15BvvFS-B4do';//何总
			$yuxing_arr[] = 'o3eaus9wDUfu01_IsRa8UZikaeiM';
			$yuxing_arr[] = 'o3eaus40d4iMREKa4pvHo1ZfaW88';//张阳
			$yuxing_arr[] = 'o3eaus026_GoLytvNkSQIrRRdtOs';//汪
			$yuxing_arr[] = 'o3eaus5JxEXUSJnCFBSpmHROmLvY';  //小葛
			$yuxing_arr[] = 'o3eauszhlzrcotkz47q2MqNzHamw';//宁佳丽
			$yuxing_arr[] = 'o3eauszQLi-MfNBPszw-ZWaZBkA8';//尹斌
			$yuxing_arr[] = 'o3eaus0NNb3jBUAdIEp--Bhdp74g';//女设计师
			$yuxing_arr[] = 'o3eaus8lUvK0eiWB2n4iU1TAdeDs';
			if( in_array( $message->FromUserName , $yuxing_arr  ) )
			{
				return "http://www.laoyou1.me/boss/tel.php";
			}
			else
			{
				return '对不起,您不是本公司员工';
			}
			//dd($message);
			return $message->FromUserName;
		}
		else
		{
			$openId = $message->FromUserName;
		//	if(  $openID == 'o3eaus8lUvK0eiWB2n4iU1TAdeDs' )

			$xiaoxi =$message->Content;
			$charu =  DB::table('moji_ceshi')->insert(['openID'=>$openId, 'moji'=>$xiaoxi ]);
			if(  $openId == 'o3eaus8lUvK0eiWB2n4iU1TAdeDs' )
			{
				//return $message->Content;
				//return base64_decode($xiaoxi);
			}
			//$openId = $message->FromUserName;
			//$userer = $userService->get($openId);
			//$name = $userer->nickname;
			//return $name;
		}
}




   });

   if(!empty($postStr)){
     $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
     $fromUsername = $postObj->FromUserName;
     $toUsername = $postObj->ToUserName;
     $keyword = trim($postObj->Content);
     $msgType = $postObj->MsgType;
     $time = time();
     $textTpl = "<xml>
         <ToUserName><![CDATA[%s]]></ToUserName>
         <FromUserName><![CDATA[%s]]></FromUserName>
         <CreateTime>%s</CreateTime>
         <MsgType><![CDATA[%s]]></MsgType>
         <Content><![CDATA[%s]]></Content>
         <FuncFlag>0</FuncFlag>
         </xml>";
         if($msgType == 'location'){
		$msgType = 'text';
   $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType,'123232');
		//echo $resultStr;
             $jss = file_get_contents("http://api.map.baidu.com/telematics/v3/local?location=$postObj->Location_Y,$postObj->Location_X&keyWord=厕所&output=json&ak=GvvubztArvpOKQ1D1qqRYiGb0sBGZfGw");
             $a = json_decode($jss,true)['pointList'];
             $ctro = '您的维度'.$postObj->Location_Y.'您的精度'.$postObj->Location_X;
             //$ctro = '您的维度';
             $contentStr = null;
             foreach ($a as $v) {
                 $contentStr .= "在$v[address]有茅坑 , 距离您$v[distance]米\n";
             }
             //$contentStr = "您的维度是: ".$postObj->Location_X.'您的精度是: '.$postObj->Location_Y;
             $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $ctro);
            // echo $resultStr;

         }

   }







      $response = $this->app->server->serve();
      // 将响应输出$response->send(); // Laravel 里请使用：
      return $response;
      }


	public function guanzhu($message){

        $openId = $message->FromUserName;
        //$name = $message->ToUserName;
	$userService = $this->app->user;
	$userer = $userService->get($openId);
        $name = $userer->nickname;

        //$user = User::where('openid',$openId)->first();
        $user =  DB::table('tbmember')->where('openID','=',$openId)->first();
         ////1:之前关注过，现在没有，修改state =1;
        if($user && $user->state == 0){
            DB::table('tbmember')->where('openID','=',$openId)->update(['state'=>1]);
        }else{
            //$userModel = new User();
            //$userModel->openid = $openId;
            //$userModel->name = $user->nickname;
            //$userModel->subtime = time();

            //$name = $user->nickname;
            $time = time();

           // $userService = $this->app->user;

            //$sex = $userer->sex;//   1是男 2是女


              //3:二维码有参数，获取二维码参数，惊醒级别处
            //$userModel->save();
       	$charu =  DB::table('tbmember')->insert(['openID'=>$openId,'vipday'=>$time]);
	//$userer = $userService->get($openId);
       // $name = $userer->nickname;
	//$name = $this->unset_biaoqing( $name );
	 if( $openId == 'o3eaus8lUvK0eiWB2n4iU1TAdeDs' )
                {
                      //  return $name;
                }

	if ( $charu )
	{
	DB::table('tbmember')->where('openID','=',$openId)->update(['name'=>$name]);

	//	if( $openId == 'o3eaus8lUvK0eiWB2n4iU1TAdeDs' )
	//	{
		//	return 1;
	//	}

	}
    	//DB::table('tbmember')->insert(['openID'=>$openId,'vipday'=>$time , 'name'=>$name]);
	//if( $openId == 'o3eaus8lUvK0eiWB2n4iU1TAdeDs' )

		//return $charu;

	//DB::table('tbmember')->where('openID','=',$openId)->update(['name'=>$name]);

                // DB::table('tbmember')->insert(['openID'=>'12']);
            //$this->qrcode($userModel->uid);
        }
	$url_guanzhu = "http://www.laoyou1.me/mould/guanzhu.php?openid=$openId&name=$name";
	$this->https2_request( $url_guanzhu  );
        // $userModel->save();

       	                        $text = new Text(['content' => "微信，
我们每天要十几次的查看:
浏览朋友圈，看别人的生活……
其实老爸老妈才是我们更该时时关注的。
现在，在这里，终于也可以随时看爸妈的“朋！友！圈！”了。
不仅安全和健康情况一目了然，
和爸妈的心也更近了！

谢谢您选用燕子智能，
随时欢迎您的任何意见和建议。
为了爸妈！

回复“说明”，查看详细界面介绍
回复“绑定”，查看绑定设备方法
回复“声音”，查看设备声音说明"]);
//	$text = new Text ( ['content'=>'
//燕子在家，守护爸妈



//第一步：回复1，如何绑定设备
//第二步：回复2，详细界面介绍
//第三步：回复3，设备声音说明
//'] );
        return $text;
      }



      public function qrcode($uid){
          $qrcode = $this->app->qrcode;
          $result = $qrcode->forever($uid);
          $ticket = $result->ticket;
          $url = $qrcode->url($ticket);
          $content = file_get_contents($url); // 得到二进制图片内容
          $path = $this->mkd().'qr_'.$uid.'.jpg';
          file_put_contents(public_path().$path, $content); // 写入文件
      }
      protected function mkd(){
          $today = date('/Y/m/');
          if(!is_dir(public_path().$today)){
              mkdir(public_path().$today,0777,true);
          }

          return $today;
      }

      public function quxiao($message)
	{
          //$info = User::where('openid',$message->FromUserName)->first();
           $info = DB::table('tbmember')->where('openID','=',$message->FromUserName)->get();
          if($info){
              // $info->state = 0;
              // $info->save();
              DB::table('tbmember')->where('openID','=',$message->FromUserName)->update(['state'=>0]);
          }
      }
	public function unset_biaoqing($str)
	{
 		$str = preg_replace_callback(
   		'/./u',
   		function (array $match) {
    		return strlen($match[0]) >= 4 ? '' : $match[0];
   		},
   		$str);

		  return $str;
 	}
	//消息模板
	public function xiaoxi(){
		//return $this->sendtpl_msg();
                  // return '123';
                  $opid='o3eaus8lUvK0eiWB2n4iU1TAdeDs';


                  $sj=date("Y/m/d H:i");
                  $tempid="qGpA2yoFIKI-VB2RAiiLpHGXxSkTBdqjGRs9HVMU58w";
                  // $tempid="qGpA2yoFIKI-VB2RAiiLpHGXxSkTBdqjGRs9HVMU58w";
                  $template=array(
                    'touser'=>$opid,
                    'template_id'=>$tempid,
                            'url'=>"http://baidu.com",
                      'topcolor'=>"#FF0000",
                    'data'=>array(
                          'first'=>array('value'=>urlencode("内测：Hommer 系统"),'color'=>"#008800"),
                          'keyword1'=>array('value'=>urlencode("您有新的消息！"),'color'=>'#000000'),
                           'keyword2'=>array('value'=>urlencode('shijan'),'color'=>'#000000'),
                           'keyword3'=>array('value'=>urlencode('哈哈哈不能'),'color'=>'#FF0000'),
                           'remark'=>array('value'=>urlencode("菜单查询详情"),'color'=>'#008800')
                          )
                  );
                  $data=urldecode(json_encode($template));
                  $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=evXZB9uE5gLA1DvHlgsa_fboFCR5yWNK3_1gl7yvQK8StkRAT6NKKMsPD3tR_8SUlbmhtv4psMvNev-faM0sUB5Q0hVxr3g5dtwwv_kiufO-fID7PVniPG_wDrfH6JBzJJLgAIAOOQ";
                    $curl = curl_init();
                    curl_setopt($curl, CURLOPT_URL, $url);
                    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
                    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
                    if (!empty($data)){
                        curl_setopt($curl, CURLOPT_POST, 1);
                        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                    }
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                     $output = curl_exec($curl);
                    curl_close($curl);
		  return ;
	}
	public  function https2_request($url,$data = null){
       $curl = curl_init();
       curl_setopt($curl, CURLOPT_URL, $url);
       curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
       curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
       if (!empty($data)){
           curl_setopt($curl, CURLOPT_POST, 1);
           curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
       }
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
       $output = curl_exec($curl);
       curl_close($curl);
       return $output;

    }
}










    // public function index()
    // {
    //
    //
    //             $muTpl = "<xml>
    //                         <ToUserName><![CDATA[%s]]></ToUserName>
    //                         <FromUserName><![CDATA[%s]]></FromUserName>
    //                         <CreateTime>%s</CreateTime>
    //                         <MsgType><![CDATA[music]]></MsgType>
    //                         <Music>
    //                         <Title><![CDATA[%s]]></Title>
    //                         <Description><![CDATA[%s]]></Description>
    //                         <MusicUrl><![CDATA[%s]]></MusicUrl>
    //                         <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
    //
    //                         </Music>
    //                     </xml>";
    //             $newTpl = "<xml>
    //                             <ToUserName><![CDATA[%s]]></ToUserName>
    //                             <FromUserName><![CDATA[%s]]></FromUserName>
    //                             <CreateTime>%s</CreateTime>
    //                             <MsgType><![CDATA[news]]></MsgType>
    //                             <ArticleCount>1</ArticleCount>
    //                             <Articles>
    //                             <item>
    //                             <Title><![CDATA[%s]]></Title>
    //                             <Description><![CDATA[%s]]></Description>
    //                             <PicUrl><![CDATA[%s]]></PicUrl>
    //                             <Url><![CDATA[%s]]></Url>
    //                             </item>
    //                             </Articles>
    //                         </xml>";
    //
    //             if($msgType == 'event'){
    //                 if($postObj->Event == 'subscribe'){
    //                 $msgType = "text";
    //                 $contentStr = "吉吉 , 欢迎你";
    //                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    //                 echo $resultStr;
    //
    //                 }
    //             }else if ($msgType == 'image'){
    //
    //                 $msgType = "text";
    //                 $jss = file_get_contents("http://apicn.faceplusplus.com/v2/detection/detect?api_key=8ab79f397dc2666fa86eec936e27d964&api_secret=xwWoI7a6HkMpP-U6N1p1jtMdInFN0gxB&url=$postObj->PicUrl&attribute=glass,pose,gender,age,race,smiling");
    //                 $a = count( json_decode($jss,true)['face']);
    //                 $contentStr = "这个图片有".$a."个人";
    //                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    //                 echo $resultStr;
    //             }else if ($msgType == 'voice'){
    //                 $msgType = "text";
    //                 $contentStr = $postObj->Recognition;
    //                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    //                 echo $resultStr;
    //             }elseelseif($msgType == 'text'){
    //                 if($keyword == 'beyond'){
    //                     $title = '音乐';
    //                     $desc = '世间纵有千万曲，人间再无黄家驹';
    //                     $murl = 'http://wxx.ittun.com/beyond.mp3';
    //                     $resultStr = sprintf($muTpl, $fromUsername, $toUsername, $time, $title, $desc , $murl ,$murl);
    //                     echo $resultStr;
    //                 }elseif($keyword == 'cang'){
    //                     $title = '图片';
    //                     $desc = '苍老湿';
    //                     $murl = 'http://wxx.ittun.com/cang.jpg';
    //                     $url = 'http://baidu.com';
    //                     $resultStr = sprintf($newTpl, $fromUsername, $toUsername, $time, $title, $desc , $murl ,$url);
    //                     echo $resultStr;
    //                 }
    //                 $msgType = "text";
    //                 if($keyword == '好'){
    //                     $contentStr = "不好 , 好什么好";
    //                 }else{
    //                     $contentStr = "别随便乱发";
    //                 }
    //                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    //                 echo $resultStr;
    //
    //
    //             } else if(!empty( $keyword )){
    //
    //             }else{
    //               echo "Input something...";
    //             }
    //
    //
    //     }else {
    //       echo "";
    //       exit;
    //         }
    // }
